package com.maodou.android.viewmodel.splash

import android.content.Context
import androidx.lifecycle.viewModelScope
import com.maodou.android.data.remote.UserRepository
import com.maodou.android.utils.PublicUtils.getAppVersionName
import com.maodou.core.base.BaseViewModel
import com.maodou.core.manager.GlobalStateManager
import com.maodou.core.network.handleResult
import com.maodou.core.network.toUserMessage
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 启动页 UI 状态
 */
data class SplashUiState(
    val isLoading: Boolean = true,
    val appName: String = "",
    val progress: Float = 0f,
    val statusText: String = "正在初始化..."
)

/**
 * 启动页 UI 事件
 */
sealed interface SplashUiEvent {
    object NavigateToMain : SplashUiEvent
    data class ShowError(val message: String) : SplashUiEvent
}

/**
 * 启动页 ViewModel
 * 处理应用初始化逻辑
 */
@HiltViewModel
class SplashViewModel @Inject constructor(
    @ApplicationContext private val appContext: Context,
    private val globalState: GlobalStateManager,
    private val repository: UserRepository,
) : BaseViewModel<SplashUiState, SplashUiEvent>() {

    val isLogin = globalState.isLoggedIn

    val isAgree = globalState.isAgree

    override fun createInitialState(): SplashUiState {
        return SplashUiState()
    }
    
    init {
        startInitialization()
    }

    fun setAgreementState(isAgree:Boolean){
        viewModelScope.launch {
            globalState.setAgreementState(isAgree)
        }
    }
    
    /**
     * 开始初始化流程
     */
    private fun startInitialization() {
        viewModelScope.launch {

            updateUiState {
                it.copy(
                    appName = "v${getAppVersionName(appContext)}",
                )
            }

            repository.getAppConfigInfo().handleResult(
                onSuccess = {
                    // 初始化完成，导航到主页
                    viewModelScope.launch {
                        delay(500)
                        emitUiEvent(SplashUiEvent.NavigateToMain)
                    }
                },
                onError = { e ->
                    updateUiState {
                        it.copy(
                            statusText = "初始化失败",
                        )
                    }
                    emitUiEvent(SplashUiEvent.ShowError("初始化失败: ${e.toUserMessage()}"))
                },
                onLoading = { load ->
                    updateUiState {
                        it.copy(
                            isLoading = load,
                        )
                    }
                }
            )
        }
    }

}